// 惊喜页面功能
document.addEventListener('DOMContentLoaded', function() {
    // 检查是否有权限访问
    if (localStorage.getItem('surpriseUnlocked') !== 'true') {
        // 没有权限，重定向到邀请函页面
        window.location.href = 'invitation.html';
        return;
    }
    
    // 加载数据
    loadJSON('data/content.json').then(data => {
        if (data && data.surprise) {
            // 填充页面内容
            document.getElementById('surprise-title').textContent = data.surprise.title;
            document.getElementById('surprise-subtitle').textContent = data.surprise.subtitle;
            document.getElementById('letter-title').textContent = data.surprise.letter.title;
            
            // 设置当前日期
            const now = new Date();
            document.getElementById('current-date').textContent = `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日`;
            
            // 生成第一次合集
            generateMoments(data.surprise.moments);
            
            // 初始化页面
            initSurprisePage(data.surprise);
        }
    });
});

// 生成第一次合集
function generateMoments(moments) {
    const container = document.getElementById('moments-container');
    if (!container || !moments) return;
    
    moments.forEach((moment, index) => {
        const card = document.createElement('div');
        card.className = 'moment-card card';
        card.style.transitionDelay = `${index * 0.3}s`;
        
        card.innerHTML = `
            <div class="moment-image-container">
                <img src="${moment.image}" alt="${moment.title}" class="moment-image">
            </div>
            <div class="moment-content">
                <h4 class="moment-title">${moment.title}</h4>
                <p class="moment-description">${moment.description}</p>
            </div>
        `;
        
        container.appendChild(card);
        
        // 滚动显示动画
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('visible');
                    observer.unobserve(entry.target);
                }
            });
        }, { threshold: 0.1 });
        
        observer.observe(card);
    });
}

// 初始化惊喜页面
function initSurprisePage(surpriseData) {
    // 页面加载时创建粒子爆炸效果
    setTimeout(() => {
        createParticleExplosion(300);
        playSound('audio/celebration.mp3');
    }, 500);
    
    // 打字机效果显示信件内容
    typeWriterEffect(
        surpriseData.letter.content,
        document.getElementById('letter-content'),
        50 // 打字速度，毫秒
    );
    
    // 再次庆祝按钮事件
    document.getElementById('celebrate-btn').addEventListener('click', () => {
        createParticleExplosion(500);
        playSound('audio/celebration.mp3');
    });
}

// 打字机效果
function typeWriterEffect(text, element, speed) {
    if (!element) return;
    
    let i = 0;
    element.textContent = '';
    
    // 添加光标
    element.style.borderRight = '0.15em solid var(--primary)';
    
    function type() {
        if (i < text.length) {
            element.textContent += text.charAt(i);
            i++;
            setTimeout(type, speed);
        } else {
            // 完成后移除光标
            element.style.borderRight = 'none';
        }
    }
    
    // 延迟开始打字效果
    setTimeout(type, 1000);
}

// 创建粒子爆炸效果
function createParticleExplosion(count) {
    const container = document.getElementById('particle-container') || createContainer('particle-container');
    
    const colors = ['#FF6B9B', '#6BCBFF', '#FFD66B', '#A78BFA', '#6BFFB8', '#FFFFFF'];
    
    // 清除现有粒子
    while (container.firstChild) {
        container.removeChild(container.firstChild);
    }
    
    // 爆炸中心
    const centerX = window.innerWidth / 2;
    const centerY = window.innerHeight / 2;
    
    for (let i = 0; i < count; i++) {
        const particle = document.createElement('div');
        particle.className = 'particle';
        
        // 随机样式
        const size = Math.random() * 8 + 2;
        particle.style.width = `${size}px`;
        particle.style.height = `${size}px`;
        particle.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
        
        // 位置在中心
        particle.style.left = `${centerX}px`;
        particle.style.top = `${centerY}px`;
        
        // 随机方向和距离
        const angle = Math.random() * Math.PI * 2;
        const distance = Math.random() * 300 + 100;
        const x = Math.cos(angle) * distance;
        const y = Math.sin(angle) * distance;
        
        // 设置自定义属性
        particle.style.setProperty('--x', `${x}px`);
        particle.style.setProperty('--y', `${y}px`);
        
        // 爆炸动画
        const duration = Math.random() * 2 + 1;
        particle.style.animation = `particle-explode ${duration}s ease-out forwards`;
        
        container.appendChild(particle);
        
        // 动画结束后移除
        setTimeout(() => {
            if (container.contains(particle)) {
                container.removeChild(particle);
            }
        }, duration * 1000);
    }
}

// 创建容器元素
function createContainer(id) {
    const container = document.createElement('div');
    container.id = id;
    document.body.appendChild(container);
    return container;
}

// 播放音效
function playSound(url) {
    const audio = new Audio(url);
    audio.volume = 0.5;
    audio.play().catch(e => console.log('播放音效失败:', e));
}
